package server;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;

public class S_GUI extends JPanel {

	/* Variables */
	// GUI components
	protected JList userList;
	private static S_BackEnd b;
	
	// Other
	private static final long serialVersionUID = 1L;
	/* Main method for the server */
	
	public static void main(String[] args) {
		
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
        	
            public void run() {
                createAndShowGUI();
            }
        });
	}
	
	/* Constructor */
	
	private S_GUI(JEditorPane serverLog) {
		b = new S_BackEnd(serverLog);
		
		JScrollPane scroller = new JScrollPane(serverLog, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		
		JButton exitButton = new JButton("Exit");
		exitButton.addActionListener(new ActionListener() {
       	 
            public void actionPerformed(ActionEvent e) {
                //Execute when button is pressed
                //serverLog.setText(serverLog.getText()+"Exiting server.\n");
                System.exit(0);
            }
        }); 
		JPanel buttonPanel = new JPanel(new BorderLayout());
		buttonPanel.add(exitButton, BorderLayout.CENTER);
		
		JPanel right = new JPanel();
		right.setLayout(new BorderLayout());
		right.add(scroller, BorderLayout.CENTER);
		right.add(buttonPanel, BorderLayout.SOUTH);
		
		String[] users = b.getUsernames();
		userList = new JList(users);
		MouseListener mouseListener = new MouseListener() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					int index = userList.locationToIndex(e.getPoint());
					System.out.println("Double clicked on Item " + index);
					displayFriends(index, b);
				}
			}
			public void mouseEntered(MouseEvent e) {
			}
			public void mouseExited(MouseEvent e) {
			}
			public void mousePressed(MouseEvent e) {
			}
			public void mouseReleased(MouseEvent e) {
			}
		};
		userList.addMouseListener(mouseListener);
		
		JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, userList, scroller);
		split.setDividerSize(3);
		this.setLayout(new BorderLayout());
		this.add(split, BorderLayout.CENTER);
		this.add(buttonPanel, BorderLayout.SOUTH);
		this.setVisible(true);
		this.setPreferredSize(new Dimension(400,600));
		
		new S_ListeningThread(b);
	}
	
    /* Other methods */
	
	private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("KC Chat - Server");

        frame.addWindowListener( new WindowAdapter() {
        	public void windowClosing(WindowEvent e) {
        		JFrame frame = (JFrame)e.getSource();

        		int result = JOptionPane.showConfirmDialog(
        				frame,
        				"Are you sure you want to exit the application?",
        				"Exit Application",
        				JOptionPane.YES_NO_OPTION);

        		if ((result == JOptionPane.YES_OPTION) && (b.getOutputStreams().size() == 0)) {
    				System.out.println("S_GUI -> size of outputStreams = "+ b.getOutputStreams().size()+ ".\n");
        				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // FIXME some how closes even with above reinforced If statement!?
        		}
        	}
        });

		final JEditorPane serverLog = new JEditorPane();
        //Create and set up the content pane.
        JPanel newContentPane = new S_GUI(serverLog);
        frame.setContentPane(newContentPane);
		
        BufferedImage icon = null;
		try {
			icon = ImageIO.read(new File("window.png"));
			frame.setIconImage(icon);
		} 
		catch (IOException e) {
			serverLog.setText(serverLog.getText()+"S_GUI -> Couldn't find frame icon!");
			//e.printStackTrace();
		}

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }
	
	/* GUI actions */
	
    protected void displayFriends(int index, S_BackEnd b) {
		ArrayList<String[]> friends = b.getUsersFriends(index);
		
		String[] friendStore = new String[friends.size()];
		for (int i = 0; i < friends.size(); i++) {
			friendStore[i] = friends.get(i)[0];
		}
		
		JDialog dialog = new JDialog();
		dialog.setTitle("Show friends");
		
		JList list = new JList(friendStore);
		
		dialog.add(list);
    	dialog.setBounds(0,0,200,300);
		dialog.setVisible(true);
    }  
}